package sskj.regulatory.presentation.screen.register

import isskj.regulatory.presentation.base_mvp.api.ApiPresenter
import sskj.regulatory.data.response.Response
import sskj.regulatory.domain.fetcher.result_listener.RequestType
import sskj.regulatory.domain.interactor.UserInteractor
import sskj.regulatory.presentation.screen.registeCaptcha.RegisterCaptchaFragment
import javax.inject.Inject

class RegisterPresenter @Inject constructor()
    : ApiPresenter<RegisterContract.View>(), RegisterContract.Presenter {

    private var requestType: RequestType = REGISTER

    private val isRegisterSuccess = { it: Response ->
        when (it.success) {
            true -> view.showRegisterYes()
            false -> view.showRegisterNo()
        }
    }

    override fun isRegister(username: String) {
        requestType = ISREGISTER
        fetch(userInteractor.isRegister(username), requestType, isRegisterSuccess)
    }

    private fun sendVCodeSuccess(phone: String, vCode: String) = { it: Response ->
        when (it.success) {
            true -> view.sendOk(phone, vCode)
            false -> view.sendError()
        }
    }

    override fun sendVCode(phone: String) {
        when (RegisterCaptchaFragment.along) {
            1L -> {
                view.sendLoading()
                requestType = REGISTER
                var vCode = ""
                for (i in 0 until 6) {
                    vCode += ((Math.random() * 9 + 1).toInt()).toString()
                }
                fetch(userInteractor.sendVCode(phone, vCode), requestType, sendVCodeSuccess(phone, vCode))
            }
            else -> {
                view.sendTimeNo()
            }
        }
    }

    override fun onRequestError(errorCode: String?, errorMessage: String?) {
        when (requestType) {
            REGISTER -> {
                view.sendError(errorMessage)
            }
            ISREGISTER -> {
                view.showError(errorMessage)
            }
            else -> {
            }
        }
    }
}